// 统一处理table的数据和请求处理
import { ref, reactive, unref } from "vue";
import type { Ref } from "vue";

// api 必传： 比如 api.admin.getAdminList
// queryParams 可选 : 比如  api.admin.getAdminList需要的参数 如 :keyword pageNum , pageSize
function useTabel<
  P,
  R extends {
    list: any;
    pageNum: number;
    pageSize: number;
    total: number;
    totalPage: number;
  }
>(api: (data?: P) => Promise<R>, queryParams?: P) {
  // 分页器
  let pagination = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0,
    totalPage: 0,
  });
  // 获取data的列表数据
  let tableData: Ref<R["list"]> = ref([]);
  async function getTableData() {
    console.log(queryParams); // 传过来的queryParams 已经变成 ref 类型
    // 定义一个普通的对象 ，遍历queryParams并将每一个key和value赋值给这个对象，得到一个新对象
    let normalQueryParams = {} as P;
    if (typeof queryParams === "object") {
      for (let key in queryParams) {
        // console.log(key);
        // console.log(unref(queryParams[key]));
        // unref 可以直接将响应式转为普通数据
        normalQueryParams[key] = unref(queryParams[key]);
      }
    }
    // console.log("...",{...normalQueryParams});
    // 发请求
    let result = await api({
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...normalQueryParams,
    });
    console.log(result);
    tableData.value = result.list;
    pagination.pageNum = result.pageNum;
    pagination.pageSize = result.pageSize;
    pagination.total = result.total;
    pagination.totalPage = result.totalPage;
  }
  getTableData();
  // 每页条数发生变化时的处理
  let handleSizeChange = (val: number) => {
    // console.log(val);
    pagination.pageSize = val;
    getTableData();
  };
  // 改变当前页数
  let handleCurrentChange = (val: number) => {
    pagination.pageNum = val;
    getTableData();
  }
  return {
    getTableData,
    tableData,
    pagination,
    handleSizeChange,
    handleCurrentChange
  };
}

export default useTabel;
